/**
 * 
 */
package com.arx.script;

import com.arx.interactive.InteractiveObject;

/**
 * @author Donald
 */
abstract class ScriptIOGroupBase extends ScriptEventStackBase {
	/**
	 * {@inheritDoc}
	 */
	public void ARX_IOGROUP_Add(final InteractiveObject io,
			final String group) {
		if (io != null
				&& group != null
				&& group.length() > 0
				&& !IsIOGroup(io, group)) {
			io.addIOGroup(group.getBytes());
		}
	}
	/**
	 * {@inheritDoc}
	 */
	public void ARX_IOGROUP_Release(final InteractiveObject io) {
		io.clearIOGroups();
		io.setNb_iogroups((short) 0);
	}
	/**
	 * {@inheritDoc}
	 */
	public void ARX_IOGROUP_Remove(final InteractiveObject io,
			final String group) {
		if (group != null
				&& group.length() > 0) {
			int toremove = -1;
			for (int i = 0; i < io.getNb_iogroups(); i++) {
				if (io.getIOGroupAsString(i) != null
						&& group.equalsIgnoreCase(io.getIOGroupAsString(i))) {
					toremove = i;
					break;
				}
			}
			if (toremove != -1) {
				if (io.getNb_iogroups() == 1) {
					io.clearIOGroups();
				} else {
					io.removeIOGroup(toremove);
				}
			}
		}
	}
	/**
	 * Determines if an {@link InteractiveObject} belongs to a specific group.
	 * @param io the {@link InteractiveObject}
	 * @param group the name of the group
	 * @return true if the {@link InteractiveObject} belongs to the group; false
	 *         otherwise
	 */
	private boolean IsIOGroup(final InteractiveObject io, final String group) {
		boolean val = false;
		for (short i = 0; i < io.getNb_iogroups(); i++) {
			if (io.getIOGroupAsString(i) != null
					&& io.getIOGroupAsString(i).equalsIgnoreCase(group)) {
				val = true;
				break;
			}
		}
		return val;
	}
}
